<template>
  <div class="rewelding-frequency">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="原料卷号">
          <el-input v-model="searchForm.entid" placeholder="输入" />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="searchForm.startDate" type="datetime" placeholder="输入" />至
          <el-date-picker v-model="searchForm.endDate" type="datetime" placeholder="输入" />
        </el-form-item>
        <el-form-item label="异常筛选">
          <el-select v-model="searchForm.flag" placeholder="请选择" clearable class="custom-select">
            <el-option label="全部" value="3" />
            <el-option label="是" value="1" />
            <el-option label="否" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      height="calc(100vh - 180px)"
      :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
      :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
      :row-style="{ background: '#0f2142' }"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="entid" label="原料卷号" width="110" align="center" />
      <el-table-column prop="extid" label="出口卷号" width="110" align="center" />
      <el-table-column prop="crew" label="班次" width="110" align="center">
        <template #default="scope">
          <span>{{ scope.row.shift=='1'?'白':'夜' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="crew" label="班组" width="110" align="center">
        <template #default="scope">
          <span>{{ scope.row.crew=='A'?'甲':scope.row.crew=='B'?'乙':scope.row.crew=='C'?'丙':'丁' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="steelGrade" label="钢种" width="110" align="center" />
      <el-table-column prop="inMatThk" label="原料厚度" width="110" align="center" />
      <el-table-column prop="outMatThk" label="出口厚度" width="110" align="center" />
      <el-table-column prop="outMatWidth" label="出口宽度" width="110" align="center" />
      <el-table-column prop="createTimes" label="创建时间" width="160" align="center" >
      </el-table-column>

      <!-- 开卷机时序 -->
      <el-table-column label="开卷机时序" align="center">
        <el-table-column prop="porExpandTimess" :label="`开卷机装卷(理论时间:${diffAnotherheadToTail || '-'}s)`" width="210" align="center">
          <template #default="scope">
            <span :class="getOverallResultClass(1,scope.row)">
              {{ parseInt(scope.row.porExpandTimess) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="headToCutterTime" :label="`开卷(理论时间:${diffArriveWait || '-'}s)`" width="180" align="center">
           <template #default="scope">
            <span :class="getOverallResultClass(2,scope.row)">
              {{ parseInt(scope.row.headToCutterTime) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="arriveWaitPosTime" :label="`穿带(理论时间:${diffFinishedToActive || '-'}s)`" width="180" align="center">
          <template #default="scope">
            <span :class="getOverallResultClass(3,scope.row)">
              {{ parseInt(scope.row.arriveWaitPosTime) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="anotherheadToweldTime" :label="`剪切(理论时间:${diffHeadToCutter || '-'}s)`" width="180" align="center">
          <template #default="scope">
            <span :class="getOverallResultClass(4,scope.row)">
              {{ parseInt(scope.row.anotherheadToweldTime) }}
            </span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 剪切异常 -->
      <el-table-column label="剪切异常" align="center">
        <el-table-column prop="headCutTimesMax" label="设定剪切次数" width="140" align="center" />
        <el-table-column prop="headCutTimesAct" label="实际剪切次数" width="140" align="center" />
      </el-table-column>

      <!-- 焊接时序 -->
      <el-table-column label="焊接时序" align="center">
        <el-table-column prop="tailToweldTime" :label="`焊前准备(理论时间:${diffPorExpand || '-'}s)`" width="210" align="center">
          <template #default="scope">
            <span :class="getOverallResultClass(5,scope.row)">
              {{ parseInt(scope.row.tailToweldTime) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="finishedWeldTime" :label="`焊接完成(理论时间:${diffStraight || '-'}s)`" width="210" align="center" >
          <template #default="scope">
            <span :class="getOverallResultClass(6,scope.row)">
              {{ parseInt(scope.row.finishedWeldTime) }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="beforeThickness" label="挖边剪切" width="140" align="center" /> -->
      </el-table-column>

      <!-- 圆盘剪时序 -->
      <el-table-column label="圆盘剪时序" align="center">
        <el-table-column prop="notchTime" label="焊缝到挖边剪切" width="150" align="center" >
          <template #default="scope">
            {{ scope.row.notchTime==null?'-':scope.row.notchTime }}
          </template>
        </el-table-column>
        <el-table-column prop="arriceTrTime" label="焊缝到圆盘剪" width="140" align="center">
          <template #default="scope">
            {{ scope.row.arriceTrTime==null?'-':scope.row.arriceTrTime }}
          </template>
        </el-table-column>
        <el-table-column prop="weldAdjustGapTime" label="圆盘剪调整" width="140" align="center" >
          <template #default="scope" >
            {{ scope.row.weldAdjustGapTime==null?'-':scope.row.weldAdjustGapTime }}
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';
import { useRoute } from "vue-router";
import { ElMessage } from 'element-plus';

const route = useRoute();

// 搜索表单数据
const searchForm = reactive({
  entid: "",
  startDate: "",
  endDate: "",
  flag:"1"
});

const diffAnotherheadToTail=ref();
const diffArriveWait=ref();
const diffFinishedToActive=ref();
const diffHeadToCutter=ref();
const diffPorExpand=ref();
const diffStraight=ref();

// 表格数据
const tableData = ref([
  {
    steelGrade: "",
    inMatThk: "",
    outMatWidth: "",
    outMatThk: "",
    crew: "",
    entid: "",
    extid: "",
    porExpandTimes: "",
    headToCutterTime: "",
    arriveWaitPosTime: "",
    anotherheadToweldTime: "",
    tailToweldTime: "",
    finishedWeldTime: "",
    headCutTimesMax: "",
    headCutTimesAct: ""
  }
  // ... 其他数据
]);

// --- Pagination ---
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: tableData.value.length
});

// 生命周期钩子
onMounted(async () => {
  const entid = route.query.entid as string;
  const cutTimes = route.query.cutTimes ? Number(route.query.cutTimes) : undefined;
  if (entid) {
    searchForm.entid = entid;
  }
  await getDiffTime();
  fetchTableData({ entid, cutTimes });
});

// 搜索方法
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  pagination.currentPage = 1;
  fetchTableData();
};

// 获取表格数据
const fetchTableData = async (extraParams?: { entid?: string; cutTimes?: number }) => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
      entid: extraParams?.entid ?? searchForm.entid,
      startDate: searchForm.startDate,
      endDate: searchForm.endDate,
      flag:searchForm.flag=='3'?'':searchForm.flag,
      diffAnotherheadToTail:diffAnotherheadToTail.value,
      diffArriveWait:diffArriveWait.value,
      diffFinishedToActive:diffFinishedToActive.value,
      diffHeadToCutter:diffHeadToCutter.value,
      diffPorExpand:diffPorExpand.value,
      diffStraight:diffStraight.value
    };
    if (extraParams?.cutTimes !== undefined) {
      params.cutTimes = extraParams.cutTimes;
    }
    if(searchForm.startDate!=''){
      params.startDate = formatDateTime(new Date(searchForm.startDate), true);
    }
    if(searchForm.endDate!=''){
      params.endDate = formatDateTime(new Date(searchForm.endDate), false);
    }
    Object.keys(params).forEach(key => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });
    console.log("params"+params)
    const response = await acidRollingApi.getAcidEfficiencyLists(params);
    const responseData = response.data;
    if (
      responseData &&
      responseData.data &&
      Array.isArray(responseData.data)
    ) {
      tableData.value = responseData.data.map((item: any) => ({
        porExpandTimess:parseFloat(item.porExpandTimes).toFixed(0),
        createTimes:item.createTime.substring(0,19),
        ...item
      }));
      pagination.total = responseData.count || responseData.data.length;
      ElMessage.success(responseData.msg || "查询成功");
    } else {
      ElMessage.info(
        responseData?.msg ||
          (response as any)?.msg ||
          "未查询到数据或响应格式不正确"
      );
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    const errorMessage =
      error.response?.data?.msg ||
      error.data?.msg ||
      error.msg ||
      error.message ||
      "获取数据失败";
    ElMessage.error(errorMessage);
    tableData.value = [];
    pagination.total = 0;
  }
};


function getDiffTime() {
  return new Promise((resolve, reject) => {
    let param2 = {};
    acidRollingApi.getDiffTime(param2).then(res => {
      if (res.data && res.data.data && res.data.data.length > 0) {
        const data = res.data.data[0];
        diffAnotherheadToTail.value = data.diffAnotherheadToTail || '-';
        diffArriveWait.value = data.diffArriveWait || '-';
        diffFinishedToActive.value = data.diffFinishedToActive || '-';
        diffHeadToCutter.value = data.diffHeadToCutter || '-';
        diffPorExpand.value = data.diffPorExpand || '-';
        diffStraight.value = data.diffStraight || '-';
        resolve(true);
      } else {
        reject();
      }
    }).catch(error => {
      // 设置默认值
      diffAnotherheadToTail.value = '-';
      diffArriveWait.value = '-';
      diffFinishedToActive.value = '-';
      diffHeadToCutter.value = '-';
      diffPorExpand.value = '-';
      diffStraight.value = '-';
      reject(error);
    });
  });
}

// 重置方法
const handleReset = () => {
  searchForm.entid = "";
  searchForm.startDate = "";
  searchForm.endDate = "";
};

// 新增格式化时间函数
function formatDateTime(date: Date, isStart: boolean = true) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d} ${isStart ? '00:00:01' : '23:59:59'}`;
}


const getOverallResultClass = (type: any, result: any) => {
  if (type == 1) {
    if (result.porExpandTimess > diffAnotherheadToTail.value) {
      return 'result-no';
    }
  }else if(type == 2){
    if (result.headToCutterTime > diffArriveWait.value) {
      return 'result-no';
    }
  }else if(type == 3){
    if (result.arriveWaitPosTime > diffFinishedToActive.value) {
      return 'result-no';
    }
  }else if(type == 4){
    if (result.anotherheadToweldTime > diffHeadToCutter.value) {
      return 'result-no';
    }
  }else if(type == 5){
    if (result.tailToweldTime > diffPorExpand.value) {
      return 'result-no';
    }
  }else if(type == 6){
    if (result.finishedWeldTime > diffStraight.value) {
      return 'result-no';
    }
  }
};



// 导出方法
const handleExport = async () => {
  // TODO: 实现导出逻辑
  const params = {
    entid: searchForm.entid || '',
    flag:searchForm.flag,
    startDate: searchForm.startDate,
    endDate: searchForm.endDate,
  };
  try {
    await acidRollingApi.exportProductionscheduleXlsx(params);
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败');
  }
};

// 页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTableData();
};
// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTableData();
};

</script>

<style scoped>
.rewelding-frequency {
  background-color: #0a1a3a;
  color: #c0c4cc;
  padding: 10px;
  height: 100%;
  /* Use 100% for layout within router-view */
  box-sizing: border-box;
  font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
  font-size: 13px;
  overflow: hidden;
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
  display: flex;
  flex-direction: column;
}

.search-form {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  flex-shrink: 0;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

:deep(.el-form-item__label) {
  color: #c0c4cc;
  white-space: nowrap;
  min-width: 65px;
  /* Match LayOutJudge */
  text-align: right;
}

:deep(.el-table__header) th {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-input__wrapper) {
  width: 180px;
}

:deep(.el-date-editor.el-input) {
  width: 180px;
}

:deep(.el-table),
:deep(.el-table__body),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__empty-block) {
  background: linear-gradient(135deg, #183c7e 0%, #0a1a3a 100%) !important;
}
:deep(.el-table th),
:deep(.el-table td) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr:hover > td) {
  background-color: #223a6b !important;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  z-index: -1;
}

:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}
:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
  border-bottom: none;
}

/* --- Pagination Panel (Styles should be consistent) --- */
.pagination-panel {
  background-color: #1c2d5a;
  padding: 8px 15px;
  border-radius: 3px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}
:deep(.el-pagination) {
  background-color: transparent !important;
}
:deep(.el-pagination__total),
:deep(.el-pagination__sizes),
:deep(.el-pagination__jump),
:deep(.el-pagination__editor),
:deep(.el-pagination button),
:deep(.el-pager li) {
  background-color: #1c2d5a !important;
  color: #7ec7ff !important;
  border: none !important;
}
:deep(.el-pager li.is-active) {
  background-color: #2979ff !important;
  color: #fff !important;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

.custom-input,
.custom-select,
.range-input,
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  height: 28px;
  line-height: 28px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 13px !important;
}

:deep(.custom-select .el-select__placeholder),
:deep(.custom-select .el-select__caret) {
  color: #c0c4cc;
}
.rewelding-frequency > *:not(:last-child) {
  margin-bottom: 15px;
}

 .result-ok {
    color: #67c23a;
    /* Green */
    font-weight: bold;
    background-color: rgba(103, 194, 58, 0.1);
    padding: 2px 6px;
    border-radius: 3px;
  }

  .result-no {
    color: #ff4d4f;
    /* Red */
    font-weight: bold;
    background-color: rgba(255, 77, 79, 0.1);
    padding: 2px 6px;
    border-radius: 3px;
  }
  .custom-select {
    width: 70px;
    /* Match LayOutJudge */
  }

</style>

